package com.netty4.http.xml;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.util.List;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;


public class HttpXmlRequestDecoder extends  AbstractHttpXmlDecoder<FullHttpRequest>{

    protected HttpXmlRequestDecoder(Class<?> clazz) {
        super(clazz);
    }
    protected HttpXmlRequestDecoder(Class<?> clazz,boolean isPrint) {
        super(clazz,isPrint);
    }

    protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List<Object> list) throws Exception {
        if(!fullHttpRequest.getDecoderResult().isSuccess()){
            sendError(channelHandlerContext,BAD_REQUEST);
            return;
        }
        HttpXmlRequest request = new HttpXmlRequest(fullHttpRequest,decode0(channelHandlerContext,fullHttpRequest.content()));
        list.add(request);
    }

    public static void sendError(ChannelHandlerContext context,HttpResponseStatus status){
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,status, Unpooled.copiedBuffer("Faliure:"+ status.toString()+"\r\n", CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE,"text/plain;charset=UTF-8");
        context.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}

